package com.enbatis.mybatisplugs.commons.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class ReadSpecXmlByDom {

    private static final Logger logger = LoggerFactory.getLogger(ReadSpecXmlByDom.class);

    private static DocumentBuilderFactory dbFactory = null;
    private static DocumentBuilder db = null;
    private static Document document = null;
    static {
        try {
            dbFactory = DocumentBuilderFactory.newInstance();
            db = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    public static  Map<String, DataCollectItem> getParseSpectroData(MultipartFile file){
      try {
        return   getParseSpectroData(file.getInputStream());
      }catch (Exception e){
          e.printStackTrace();
      }
       return  null;
    }
    public static  Map<String, DataCollectItem> getParseSpectroData(File f){

        try {
            FileInputStream io=new FileInputStream(f);
          return   getParseSpectroData(io);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws Exception{
        FileInputStream file=new FileInputStream("D:\\Analysen_271.XML");

        getDZParseSpectroData(file,"Analysen_272");
    }

    public static synchronized    Map<String, DataCollectItem> getDZParseSpectroData(InputStream io,String name){
        //将给定 URI 的内容解析为一个 XML 文档,并返回Document对象

        try {
            BufferedReader br= new BufferedReader(new InputStreamReader(io,"UTF-8"));
            InputSource is = new InputSource(br);
            String s;
            StringBuffer sb = new StringBuffer();
            while((s=br.readLine()) != null){
                sb.append(s);
            }

            if (!sb.toString().contains("</Result>")){
                sb.append("/Result>");
                File fileTemp=File.createTempFile(name.replace(".XML",""),".XML");
                OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(fileTemp));
                BufferedWriter writer = new BufferedWriter(write);
                writer.write(sb.toString());
                writer.flush();
                write.close();
                writer.close();
                document = db.parse(fileTemp);

                fileTemp.delete();
            }else{
                document = db.parse(is);
            }
        }catch (Exception e){

            logger.error("---------dzspec29解析失败"+e.getMessage());
            e.printStackTrace();
        }
        //按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList
        Node sampleNode = document.getElementsByTagName("Sample").item(0);
        NamedNodeMap sampleNamedMap=  sampleNode.getAttributes();
        String sampleCode=  sampleNamedMap.getNamedItem("Name").getNodeValue();

        Map<String, DataCollectItem> itemValueMap=new HashMap<>();
        if (itemValueMap.get("sampleName")==null){
            DataCollectItem collectItem= new DataCollectItem();
            collectItem .setSampleSn(sampleCode);
            itemValueMap.put("sampleName",collectItem);
        }
        System.out.println("样品编号为："+sampleCode);

        //遍历books

        NodeList resultValuesNodes=document.getElementsByTagName("ResultValues");
        int  resultValuesLength=resultValuesNodes.getLength();

        for (int i=0;i<resultValuesLength;i++){


            Node resultNode=resultValuesNodes.item(i);
            String nodeName=  resultNode.getNodeName();


            NamedNodeMap nodeResultMap = resultNode.getAttributes();
            Node typeNode= nodeResultMap.getNamedItem("Type");
            if (null==typeNode|| StringUtils.isBlank(typeNode.getNodeValue())){
                continue;
            }
            String type=typeNode.getNodeValue();
            if ("Element".equals(type)){
                String itemName=nodeResultMap.getNamedItem("IDName").getNodeValue();

                NodeList childList= resultNode.getChildNodes();
                int lengthChild=childList.getLength();
                Map<String ,Node> mapNodeList=new HashMap<>();

                for (int j=0;j<lengthChild;j++) {
                    Node child=childList.item(j);
                    if (!(child instanceof Element)){
                        continue;
                    }

                    String childName=  child.getNodeName();
                    NamedNodeMap childMap=  child.getAttributes();
                    Node childType= childMap.getNamedItem("Type");
                    if (null!=childType){
                        mapNodeList.put(childType.getNodeValue(),child);
                    }
                }

                if (mapNodeList.size()==1){
                    for (Map.Entry<String,Node> e:mapNodeList.entrySet()) {
                        String value=  e.getValue().getFirstChild().getNodeValue();
                        DataCollectItem dataCollectItem=new DataCollectItem();
                        dataCollectItem.setName(itemName);
                        dataCollectItem.setSampleSn(sampleCode);
                        dataCollectItem.setTrueValue(value);
                        itemValueMap.put(itemName,dataCollectItem);
                    }

                }else{
                    for (Map.Entry<String,Node> e:mapNodeList.entrySet()) {
                        if ("Conc Typecorr".equals(e.getKey())){
                            String value=  e.getValue().getFirstChild().getNodeValue();
                            DataCollectItem dataCollectItem=new DataCollectItem();
                            dataCollectItem.setName(itemName);
                            dataCollectItem.setSampleSn(sampleCode);
                            dataCollectItem.setTrueValue(value);
                            itemValueMap.put(itemName,dataCollectItem);
                        }

                    }

                }
            }
        }

        try {
            io.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return itemValueMap;

    }



    public static  Map<String, DataCollectItem> getDZParseSpectroData(File file) {
        //将给定 URI 的内容解析为一个 XML 文档,并返回Document对象
        FileInputStream io=null;
        try {
             io =new FileInputStream(file);
            BufferedReader br= new BufferedReader(new InputStreamReader(io,"GBK"));
            InputSource is = new InputSource(br);
            String s;
            StringBuffer sb = new StringBuffer();
            while((s=br.readLine()) != null){
                sb.append(s);
            }

            if (!sb.toString().contains("</Result>")){
                sb.append("/Result>");
                File fileTemp=File.createTempFile(file.getName().replace(".XML",""),".XML");
                OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(fileTemp));
                BufferedWriter writer = new BufferedWriter(write);
                writer.write(sb.toString());
                writer.flush();
                write.close();
                writer.close();
                document = db.parse(fileTemp);

                fileTemp.delete();
            }else{
                document = db.parse(file);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList
        Node sampleNode = document.getElementsByTagName("Sample").item(0);
        NamedNodeMap sampleNamedMap=  sampleNode.getAttributes();
        String sampleCode=  sampleNamedMap.getNamedItem("Name").getNodeValue();

        Map<String, DataCollectItem> itemValueMap=new HashMap<>();
        if (itemValueMap.get("sampleName")==null){
            DataCollectItem collectItem= new DataCollectItem();
            collectItem .setSampleSn(sampleCode);
            itemValueMap.put("sampleName",collectItem);
        }
        System.out.println("样品编号为："+sampleCode);

        //遍历books

        NodeList resultValuesNodes=document.getElementsByTagName("ResultValues");
        int  resultValuesLength=resultValuesNodes.getLength();

        for (int i=0;i<resultValuesLength;i++){


            Node resultNode=resultValuesNodes.item(i);
            String nodeName=  resultNode.getNodeName();


            NamedNodeMap nodeResultMap = resultNode.getAttributes();
            Node typeNode= nodeResultMap.getNamedItem("Type");
            if (null==typeNode|| StringUtils.isBlank(typeNode.getNodeValue())){
                continue;
            }
            String type=typeNode.getNodeValue();
            if ("Element".equals(type)){
                String itemName=nodeResultMap.getNamedItem("IDName").getNodeValue();

                NodeList childList= resultNode.getChildNodes();
                int lengthChild=childList.getLength();
                Map<String ,Node> mapNodeList=new HashMap<>();

                for (int j=0;j<lengthChild;j++) {
                    Node child=childList.item(j);
                    if (!(child instanceof Element)){
                        continue;
                    }

                    String childName=  child.getNodeName();
                    NamedNodeMap childMap=  child.getAttributes();
                    Node childType= childMap.getNamedItem("Type");
                    if (null!=childType){
                        mapNodeList.put(childType.getNodeValue(),child);
                    }
                }

                if (mapNodeList.size()==1){
                    for (Map.Entry<String,Node> e:mapNodeList.entrySet()) {
                        String value=  e.getValue().getFirstChild().getNodeValue();
                        DataCollectItem dataCollectItem=new DataCollectItem();
                        dataCollectItem.setName(itemName);
                        dataCollectItem.setSampleSn(sampleCode);
                        dataCollectItem.setTrueValue(value);
                        itemValueMap.put(itemName,dataCollectItem);
                    }

                }else{
                    for (Map.Entry<String,Node> e:mapNodeList.entrySet()) {
                        if ("Conc Typecorr".equals(e.getKey())){
                            String value=  e.getValue().getFirstChild().getNodeValue();
                            DataCollectItem dataCollectItem=new DataCollectItem();
                            dataCollectItem.setName(itemName);
                            dataCollectItem.setSampleSn(sampleCode);
                            dataCollectItem.setTrueValue(value);
                            itemValueMap.put(itemName,dataCollectItem);
                        }

                    }

                }



            }
        }

        try {
            io.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return itemValueMap;
    }




    public static synchronized  Map<String, DataCollectItem> getParseSpectroData(InputStream io) {
        //将给定 URI 的内容解析为一个 XML 文档,并返回Document对象
       try {
           document = db.parse(io);
       }catch (Exception e){
           e.printStackTrace();
       }
        //按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList
        Node sampleNode = document.getElementsByTagName("Sample").item(0);
        NamedNodeMap sampleNamedMap=  sampleNode.getAttributes();
         String sampleCode=  sampleNamedMap.getNamedItem("Name").getNodeValue();

        Map<String, DataCollectItem> itemValueMap=new HashMap<>();
        if (itemValueMap.get("sampleName")==null){
            DataCollectItem collectItem= new DataCollectItem();
            collectItem .setSampleSn(sampleCode);
            itemValueMap.put("sampleName",collectItem);
        }
        System.out.println("样品编号为："+sampleCode);

        //遍历books

        NodeList resultValuesNodes=document.getElementsByTagName("ResultValues");
        int  resultValuesLength=resultValuesNodes.getLength();

        for (int i=0;i<resultValuesLength;i++){


             Node resultNode=resultValuesNodes.item(i);
             String nodeName=  resultNode.getNodeName();


             NamedNodeMap nodeResultMap = resultNode.getAttributes();
             Node typeNode= nodeResultMap.getNamedItem("Type");
             if (null==typeNode|| StringUtils.isBlank(typeNode.getNodeValue())){
                 continue;
             }
             String type=typeNode.getNodeValue();
             if ("Element".equals(type)){
                 String itemName=nodeResultMap.getNamedItem("IDName").getNodeValue();

                 NodeList childList= resultNode.getChildNodes();
                 int lengthChild=childList.getLength();
                 Map<String ,Node> mapNodeList=new HashMap<>();

                 for (int j=0;j<lengthChild;j++) {
                     Node child=childList.item(j);
                     if (!(child instanceof Element)){
                         continue;
                     }

                     String childName=  child.getNodeName();
                     NamedNodeMap childMap=  child.getAttributes();
                     Node childType= childMap.getNamedItem("Type");
                     if (null!=childType){
                         mapNodeList.put(childType.getNodeValue(),child);
                    }
                 }

                 if (mapNodeList.size()==1){
                     for (Map.Entry<String,Node> e:mapNodeList.entrySet()) {
                         String value=  e.getValue().getFirstChild().getNodeValue();
                         DataCollectItem dataCollectItem=new DataCollectItem();
                         dataCollectItem.setName(itemName);
                         dataCollectItem.setSampleSn(sampleCode);
                         dataCollectItem.setTrueValue(value);
                         itemValueMap.put(itemName,dataCollectItem);
                     }

                 }else{
                     for (Map.Entry<String,Node> e:mapNodeList.entrySet()) {
                         if ("Conc Typecorr".equals(e.getKey())){
                             String value=  e.getValue().getFirstChild().getNodeValue();
                             DataCollectItem dataCollectItem=new DataCollectItem();
                             dataCollectItem.setName(itemName);
                             dataCollectItem.setSampleSn(sampleCode);
                             dataCollectItem.setTrueValue(value);
                             itemValueMap.put(itemName,dataCollectItem);
                         }

                     }

                 }



             }
        }

        try {
            io.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return itemValueMap;
    }



}